<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="search">
        <el-form-item>
          <el-input v-model="search.keyWord" placeholder="关键词"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getEmployees">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="importEmp">导入员工</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="exportEmp">导出员工</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="pageInfo.list" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="username" label="员工名称" width="120" sortable>
      </el-table-column>
      <el-table-column prop="password" label="员工密码" width="120" sortable>
      </el-table-column>
      <el-table-column prop="email" label="员工邮箱" width="190" sortable>
      </el-table-column>
      <el-table-column prop="headImage" label="员工头像" width="190" sortable>
      </el-table-column>
      <el-table-column prop="age" label="员工年龄" width="100" sortable>
      </el-table-column>
      <el-table-column prop="department.name" label="员工部门" width="150" sortable>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
          <el-button type="success" size="small" @click="handleRole(scope.$index, scope.row)">设置角色</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <!--
              @size-change: 当涉及的每页条数发生改变的时候触发的函数
              @current-change: 页数发生改变
              :current-page: 当前第几页
              :page-sizes="[3, 5, 7, 9]": 设定每页的条数
              :page-size="this.search.pageSize": 每页的条数
      -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="this.search.currentPage"
          :page-sizes="[3, 5, 7, 9,10]"
          :page-size="this.search.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total"
          style="float: right">
      </el-pagination>
    </el-col>

    <!--编辑/新增界面-->
    <el-dialog title="编辑" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="员工名称" prop="username">
          <el-input v-model="saveForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工密码" prop="password">
          <el-input v-model="saveForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工邮箱" prop="email">
          <el-input v-model="saveForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工头像" prop="headImage">
          <el-input v-model="saveForm.headImage" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工年龄" prop="age">
          <el-input v-model="saveForm.age" auto-complete="off"></el-input>
        </el-form-item>
        <!--下拉选项
          :key=""  //唯一标识
          :label 选择之后展示到选择框中的值
          :value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
             必须要写  value-key="id"
        -->
        <!--        <el-form-item label="部门" prop="department">-->
        <!--          <el-select v-model="saveForm.department" clearable value-key="id" placeholder="请选择">-->
        <!--            <el-option-->
        <!--                v-for="item in departments"-->
        <!--                :key="item.id"-->
        <!--                :label="item.name"-->
        <!--                :value="item">-->
        <!--              <span style="float: left">{{ item.name }}</span>-->
        <!--              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.email }}</span>-->
        <!--            </el-option>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item label="部门">
          <el-cascader v-model="saveForm.department"
                       :options="deptTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}" clearable></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--    上传界面-->
    <el-dialog title="文件导入" :visible.sync="importFormVisible" :close-on-click-modal="false">
        <!--
            action 必选参数,上传的地址 string
            on-preview 点击文件列表中已上传的文件是的钩子 function(file)
            on-remove 文件列表溢出文件是的钩子 function(file, fileList)
            before-remove 删除文件之前的钩子,参数为上传的文件和文件列表,若返回false或者返回Promise 且被reject,则停止删除 function(file, fileList)
            multiple 是否支持多选文件  boolean
            limit 最大允许上传的个数 number
            on-exceed 文件超出个数限制时的钩子 function(file, fileList)
            file-list 上传的文件列表,例如: [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}]

            通过 slot 你可以传入自定义的上传按钮类型和文字提示。可通过设置limit和on-exceed来限制上传文件的个数和定义超出限制时的行为。可通过设置before-remove来阻止文件移除操作。
        -->
        <p>请选择要上传的文件:</p>
        <el-upload
            action="#"
            accept=".xls,.xlsx"
            ref="upload"
            :http-request="httpRequest"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :limit="1"
            >
          <el-button size="large" type="primary">导入员工</el-button>
          <div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件，且不超过500kb</div>
        </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="importFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="importSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

<!--    设置角色界面 一个用户可能有多种角色-->
    <el-dialog title="设置角色" :visible.sync="roleFormVisible" :close-on-click-modal="false">
      <el-form :model="roleForm" label-width="80px"  ref="roleForm">
        <el-form-item label="用户名称" prop="name">
          <el-input v-model="roleForm.username" disabled auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <!--
            :data tree的数据源
            show-checkbox 显示勾选框
            node-key="id" 以id为唯一值
            :props="defaultProps" 标签显示规则
          -->
          <el-tree
              :data="roleTree"
              show-checkbox
              default-expand-all
              node-key="id"
              ref="tree"
              highlight-current
              :props="roleDefaultProps">
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="roleFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="roleSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>

import department from "./Department";

export default {
  data() {
    return {
      search: {
        keyWord: '',
        pageSize: 10,
        currentPage: 1
      },
      pageInfo: {
        list: [],
        total: 0
      },
      listLoading: false,
      sels: [],//列表选中列

      saveFormVisible: false,//编辑界面是否显示
      editLoading: false,
      importFormVisible: false,
      saveFormRules: {
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ]
      },
      //编辑界面数据 不能把null赋值给对象
      saveForm: {
        id: null,
        username: '',
        password: '',
        email: '',
        headImage: '',
        age: null,
        department: {
          id: null,
          name: "",
        }
      },
      departments: [],
      deptTree: [],

      fileList: [],
      errDate: [],
      // 设置角色
      roleFormVisible: false,
      roleForm:{
        id:null,
        name:"",
        roles:[]
      },
      roleTree:[],
      roleDefaultProps:{
        children: 'children',
        label: 'name'
      }
    }
  },
  methods: {
    // 点击设置角色
    handleRole(index,row){
      this.roleFormVisible = true;
      this.getRoleTree()
      // console.log(row)
      // 回显用户名
      this.roleForm = row;
      // 回显角色
      this.queryRoleById(row.id)
    },
    // 点击提交按钮
    roleSubmit(){
      this.roleForm.roles = this.$refs.tree.getCheckedNodes();
      // console.log(this.roleForm.roles)
      this.$http.put("/employeeRole/role/", this.roleForm)
          .then(res => {
            this.roleFormVisible = false;
            this.$message({message: "角色修改成功", type: "success"});
          }).catch(res => {

      })
    },
    // 根据用户id查询角色
    queryRoleById(id){
      this.$http.get("/employeeRole/role/"+id)
          .then(result => {
            result = result.data;
            if (result.success){
              this.$refs.tree.setCheckedKeys(result.data);
            }
          })
          .catch(result => {})

    },
    // 获取角色树
    getRoleTree(){
      this.$http.get("/role")
          .then(result => {
            result = result.data;
            if (result.success){
              this.roleTree = result.data;
            }
          })
          .catch(result => {})
    },
    handleRemove() {
      this.fileList.pop();
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    // 将row添加给fileList数组
    httpRequest(row) {
      console.log("这里",row)
      this.fileList.push(row);
      // console.log("fileList",this.fileList)
    },
    // 点击上传提交
    importSubmit() {
      // // 创建 FormData 对象
      const formData = new FormData();

      if (this.fileList.length > 0) {
      // 将文件列表添加到 FormData 中
        this.fileList.forEach(x => {
          formData.append('file', x.file);
        });
        console.log("2222222222222222",formData)
        this.$http.post("/employee/importExcel", formData)
            .then(result => {
              result = result.data
              if (result.success) {
                console.log(result.data)
                if (result.data.length > 0) {
                  result.data.forEach(emp => {
                    this.errDate.push(emp.id)
                  })
                  this.$confirm("id为" + this.errDate + "的数据格式错误保存失败,已经导出错误数据", '提示', {}).then(() =>{})
                } else {
                  this.$confirm("导入成功", '提示',{}).then(()=>{})
                }
                this.importFormVisible = false;
                this.$refs.upload.clearFiles()
                this.fileList = []
                this.errDate = [];
                this.getEmployees();
              }
            })
            .catch(result => {

            })
      }else {
        alert("先上传,再点击提交!!!")
      }
    },
    // 点击导入员工按钮,弹出上传界面
    importEmp() {
      this.importFormVisible = true;
    },

    // 点击导出
    exportEmp() {
      this.$confirm('确认导出全部数据吗?', '提示', {
        type: 'warning'
      }).then(() => {
        // 发起Ajax请求触发后端导出 Excel 的方法
        // 使用axios库进行请求，确保你的项目中已经引入了axios
        // this.$http.get('/employee/exportExcel', {
        //   responseType: 'blob' // 响应类型为二进制数据流
        // }).then(response => {
        //   // 创建一个blob URL，用于下载
        //   const blob = new Blob([response.data], { type: 'application/octet-stream' });
        //   const link = document.createElement('a');
        //   link.href = window.URL.createObjectURL(blob);
        //   link.download = '员工导出表.xlsx'; // 请替换为实际的文件名
        //   document.body.appendChild(link);
        //   link.click();
        //   document.body.removeChild(link);
        // }).catch(error => {
        //   console.error('导出失败:', error);
        //   // 处理错误
        // });
        this.$http.post("/employee/exportExcel",this.search)
            .then(result => {
              result = result.data
              if (result.success) {
                this.$message({
                  type: 'success',
                  message: '导出成功!'
                });
              }
            })
            .catch(result => {
              this.$message({
                type: 'info',
                message: '已取消导出'
              });
            })
      }).catch(() => {
        console.log("---------导出失败---------")
      });
    },
    //性别显示转换
    formatSex: function (row, column) {
      return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
    },
    handleSizeChange(val) {
      // 每页条数
      this.search.pageSize = val;
      this.search.currentPage = 1;
      this.getEmployees();
    },
    handleCurrentChange(val) {
      this.search.currentPage = val;
      this.getEmployees();
    },
    // 获取联级部门的id和name
    getTree() {
      this.$http.get("/department/tree")
          .then(result => {
            // console.log("dajiahoa",result.data.data)
            this.deptTree = result.data.data;

          })
          .catch(result => {

          })
    },
    // 获取部门信息
    getDepartments() {
      this.$http.get("/department")
          .then(result => {

            let data = result.data;
            if (data.success) {
              this.departments = data.data;
            }
            // console.log("部门信息为",this.departments)
          })
          .catch(result => {

          })
    },
    //获取部门列表
    getEmployees() {
      // this.listLoading = true;
      // 发送axios请求
      this.$http.post("/employee", this.search)
          .then(result => {
            // console.log("这里是getEmployees",result.data);
            let data = result.data;
            if (data.success) {
              // this.pageInfo.list = data.data.list;
              // this.pageInfo.total = data.data.total;
              this.pageInfo = data.data;
            }
            this.listLoading = false;
          })
          .catch(result => {

          });
    },
    //删除
    handleDel: function (index, row) {
      // console.log(row)
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        this.$http.delete("/employee/" + row.id)
            .then(result => {
              let data = result.data;
              if (data.success) {
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
                this.search.currentPage = 1;
                this.getEmployees();
                this.listLoading = false;
              }
            })
            .catch(result => {

            })
      }).catch(() => {

      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.saveFormVisible = true;
      this.saveForm = Object.assign({}, row);
      if (!row.department) {
        // this.saveForm.department = {id: null, name: ""}
      } else {
        console.log("这里是row", row.department.path)
        // 如果父部门不为空,获取path
        let split = row.department.path.split("/");
        // console.log(split)
        let path = [];
        // 从一开始因为split数组里第一个元素为''
        for (let i = 1; i < split.length; i++) {
          // push往数组中添加,pop是移除
          path.push(Number.parseInt(split[i]));
          this.saveForm.department = path;
        }
        console.log(this.saveForm.department)
      }
      this.getDepartments();
      this.getTree();
    },
    //显示新增界面
    handleAdd: function () {
      this.saveFormVisible = true;
      this.saveForm = {
        id: null,
        username: '',
        password: '',
        email: '',
        headImage: '',
        age: null,
        department: {
          id: null,
          name: ""
        }
      };
      this.getDepartments();
      this.getTree();
    },
    //编辑
    editSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;
            //NProgress.start();
            // 判断,如果父部门不为空,就转换成对象,原本是数组
            // console.log(this.saveForm.parent);
            // console.log(this.saveForm.parent.id);
            // 有可能长度为0
            // if (this.saveForm.parent.length >= 0) {
            //   if (this.saveForm.parent.length == 0) {
            //     this.saveForm.parent = {
            //       id: null
            //     }
            //   } else {
            //     this.saveForm.parent = {
            //       id: this.saveForm.parent[this.saveForm.parent.length - 1]
            //     }
            //   }
            // }
            this.$http.put("/employee", this.saveForm)
                .then(result => {
                  let data = result.data;
                  if (data.success) {
                    this.$message({
                      message: '操作成功',
                      type: 'success'
                    });
                    this.search.currentPage = 1;
                    this.getEmployees();
                    this.editLoading = false;
                    this.saveFormVisible = false;
                  }
                })
                .catch(result => {

                })
          });
        }
      });
    },
    //新增
    addSubmit: function () {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.addForm);
            para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
            addUser(para).then((res) => {
              this.addLoading = false;
              //NProgress.done();
              this.$message({
                message: '提交成功',
                type: 'success'
              });
              this.$refs['addForm'].resetFields();
              this.addFormVisible = false;
              this.getUsers();
            });
          });
        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        this.$http.patch("/employee/", ids)
            .then(result => {
              let data = result.data;
              if (data.success) {
                this.$message({
                  message: '批量删除成功',
                  type: 'success'
                });
                this.search.currentPage = 1;
                this.getEmployees();
                this.listLoading = false;
              }
            })
            .catch(result => {

            })
      }).catch(() => {

      });
    }
  },
  mounted() {
    this.getEmployees();
  }
}

</script>

<style scoped>

</style>